﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Wicresoft.Framework.Organization;

/// <summary>
/// Summary description for WebCommon
/// </summary>
public class WebCommon
{
    public WebCommon()
    {
        //
        // TODO: Add constructor logic here
        //
    }

    public static string GetConfig(string KeyName)
    {
        try
        {
            return ConfigurationManager.AppSettings[KeyName];
        }
        catch
        {
            return string.Empty;
        }
    }

    public static string GetFileIcon(string fileName)
    {
        fileName = fileName.ToLower();
        if (fileName.EndsWith(".doc") || fileName.EndsWith(".wbk") || fileName.EndsWith(".dot"))
            return "/UI Standard/icon/FileType/doc.gif";
        else if (fileName.EndsWith(".mda") || fileName.EndsWith(".mdt") || fileName.EndsWith(".mdb")
            || fileName.EndsWith(".mdn") || fileName.EndsWith(".adn") || fileName.EndsWith(".maw")
            || fileName.EndsWith(".mdz") || fileName.EndsWith(".mag") || fileName.EndsWith(".maf")
            || fileName.EndsWith(".mam") || fileName.EndsWith(".mde") || fileName.EndsWith(".mad")
            || fileName.EndsWith(".adp") || fileName.EndsWith(".ade") || fileName.EndsWith(".maq")
            || fileName.EndsWith(".ldb") || fileName.EndsWith(".mar") || fileName.EndsWith(".mas")
            || fileName.EndsWith(".mat") || fileName.EndsWith(".mav") || fileName.EndsWith(".mdw"))
            return "/UI Standard/icon/FileType/Access.gif";
        else if (fileName.EndsWith(".chm"))
            return "/UI Standard/icon/FileType/chm.gif";
        else if (fileName.EndsWith(".exe") || fileName.EndsWith(".com"))
            return "/UI Standard/icon/FileType/exe.gif";
        else if (fileName.EndsWith(".gif") || fileName.EndsWith(".bmp") || fileName.EndsWith(".jpg")
            || fileName.EndsWith(".jpeg") || fileName.EndsWith(".jpe") || fileName.EndsWith(".pcx")
            || fileName.EndsWith(".png") || fileName.EndsWith(".pic") || fileName.EndsWith(".psd")
            || fileName.EndsWith(".tif") || fileName.EndsWith(".tiff"))
            return "/UI Standard/icon/FileType/gif.gif";
        else if (fileName.EndsWith(".hlp"))
            return "/UI Standard/icon/FileType/help.gif";
        else if (fileName.EndsWith(".htm") || fileName.EndsWith(".html") || fileName.EndsWith(".htw")
            || fileName.EndsWith(".htx") || fileName.EndsWith(".url"))
            return "/UI Standard/icon/FileType/htm.gif";
        else if (fileName.EndsWith(".mp2") || fileName.EndsWith(".mpa") || fileName.EndsWith(".mp3")
            || fileName.EndsWith(".wav") || fileName.EndsWith(".wma"))
            return "/UI Standard/icon/FileType/mp3.gif";
        else if (fileName.EndsWith(".rm") || fileName.EndsWith(".ra") || fileName.EndsWith(".ram")
            || fileName.EndsWith(".rmvb"))
            return "/UI Standard/icon/FileType/ra.gif";
        else if (fileName.EndsWith(".rar") || fileName.EndsWith(".r01") || fileName.EndsWith(".r02")
            || fileName.EndsWith(".r03") || fileName.EndsWith(".r04") || fileName.EndsWith(".r05")
            || fileName.EndsWith(".r06") || fileName.EndsWith(".r07") || fileName.EndsWith(".r08")
            || fileName.EndsWith(".r09") || fileName.EndsWith(".r10") || fileName.EndsWith(".7z")
            || fileName.EndsWith(".arj") || fileName.EndsWith(".jar") || fileName.EndsWith(".lzh")
            || fileName.EndsWith(".lha") || fileName.EndsWith(".iso"))
            return "/UI Standard/icon/FileType/rar.gif";
        else if (fileName.EndsWith(".swf"))
            return "/UI Standard/icon/FileType/swf.gif";
        else if (fileName.EndsWith(".txt"))
            return "/UI Standard/icon/FileType/txt.gif";
        else if (fileName.EndsWith(".zip") || fileName.EndsWith(".cab"))
            return "/UI Standard/icon/FileType/zip.gif";
        else if (fileName.EndsWith(".xls") || fileName.EndsWith(".xla") || fileName.EndsWith(".xlk")
            || fileName.EndsWith(".csv") || fileName.EndsWith(".dif") || fileName.EndsWith(".xlt")
            || fileName.EndsWith(".xlv") || fileName.EndsWith(".xlw") || fileName.EndsWith(".xll"))
            return "/UI Standard/icon/FileType/xls.gif";
        else
            return "/UI Standard/icon/FileType/other.gif";

    }

    /// <summary>
    /// 对DataTable进行分页,起始页为1
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="PageIndex"></param>
    /// <param name="PageSize"></param>
    /// <returns></returns>
    public static DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize)
    {
        if (PageIndex == 0)
            return dt;
        DataTable newdt = dt.Copy();
        newdt.Clear();

        int rowbegin = (PageIndex - 1) * PageSize;
        int rowend = PageIndex * PageSize;

        if (rowbegin >= dt.Rows.Count)
            return newdt;

        if (rowend > dt.Rows.Count)
            rowend = dt.Rows.Count;
        for (int i = rowbegin; i <= rowend - 1; i++)
        {
            DataRow newdr = newdt.NewRow();
            DataRow dr = dt.Rows[i];
            foreach (DataColumn column in dt.Columns)
            {
                newdr[column.ColumnName] = dr[column.ColumnName];
            }
            newdt.Rows.Add(newdr);
        }

        return newdt;
    }

    public static string GetHTMLStyleStr(string oldval)
    {
        string retVal;
        retVal = HttpUtility.HtmlEncode(oldval);
        retVal = retVal.Replace("   ", "&nbsp;");
        retVal = retVal.Replace("\r\n", "<br   />");
        return retVal;
    }

    public static string GetStandardStyleStr(string oldval)
    {
        string retVal;
        retVal = oldval.Replace("&nbsp;", "   ");
        retVal = retVal.Replace("<br   />", "\r\n");
        retVal = HttpUtility.HtmlDecode(retVal);
        return retVal;
    }

    public static string GetThirdLevelDepartmentName(Guid mainDeptID)
    {
        Department currMainDept = OrganizationHelper.GetDepartmentInfo(mainDeptID);
        if (currMainDept != null)
        {
            string deptPath = currMainDept.IDPath;
            string[] deptIDs = deptPath.Split('/');
            string retDeptID = string.Empty;
            if (deptIDs.Length >= 4)
            {
                retDeptID = deptIDs[3];
            }
            if (!string.IsNullOrEmpty(retDeptID))
            {
                Department thirdDept = OrganizationHelper.GetDepartmentInfo(new Guid(retDeptID));
                return thirdDept.DisplayName;
            }
        }
        return string.Empty;

    }

    public static void ShowMessage(System.Web.UI.Page page, string message)
    {
        string msg = WebCommon.CsStyledEncode(message);
        page.ClientScript.RegisterStartupScript(page.GetType(), "MsgScript", "<script language='javascript'>" +
            "function AlertMsg()" +
            "{" +
            "if(document.readyState=='complete')" +
            "alert('" + msg + "');" +
            "else " +
            "setTimeout('AlertMsg()',1);" +
            "}" +
            "AlertMsg();" +
            "</script>");
    }

    public static void ShowMessageAndClose(System.Web.UI.Page page, string message)
    {
        string msg = WebCommon.CsStyledEncode(message);
        page.ClientScript.RegisterStartupScript(page.GetType(), "MsgScript", "<script language='javascript'>" +
            "function AlertCloseMsg()" +
            "{" +
            "if(document.readyState=='complete'){" +
            "alert('" + msg + "');" +
            "close(); }" +
            "else " +
            "setTimeout('AlertCloseMsg()',1);" +
            "}" +
            "AlertCloseMsg();" +
            "</script>");
    }

    public static void ShowMessageAndClose(System.Web.UI.Page page, string message, string returnValue)
    {
        string msg = WebCommon.CsStyledEncode(message);
        page.ClientScript.RegisterStartupScript(page.GetType(), "MsgScript", "<script language='javascript'>" +
            "function AlertCloseMsg()" +
            "{" +
            "if(document.readyState=='complete'){" +
            "alert('" + msg + "');returnValue='" + returnValue + "';" +
            "close(); }" +
            "else " +
            "setTimeout('AlertCloseMsg()',1);" +
            "}" +
            "AlertCloseMsg();" +
            "</script>");
    }


    public static bool OpenWindow(System.Web.UI.Page page, string window)
    {
        window = UrlNocache(window);
        page.RegisterStartupScript(Guid.NewGuid().ToString(), "<script language='javascript'>window.open('" + window + "');</script>");
        return true;
    }

    public static bool OpenWindow(System.Web.UI.Page page, string window, string target)
    {
        window = UrlNocache(window);
        page.RegisterStartupScript(Guid.NewGuid().ToString(), "<script language='javascript'>window.open('" + window + "', '" + target + "');</script>");
        return true;
    }

    public static bool OpenWindow(System.Web.UI.Page page, string window, string target, string attribute)
    {
        window = UrlNocache(window);
        page.RegisterStartupScript(Guid.NewGuid().ToString(), "<script language='javascript'>window.open('" + window + "', '" + target + "', '" + attribute + "');</script>");
        return true;
    }

    public static string Cut(object oStr, int count)
    {
        int len = count * 2;
        if (len <= 0) return oStr.ToString();

        string str = oStr.ToString();

        int curIdx = 0;
        int curLen = 0;
        int cutIdx = 0;
        int cutLen = 0;
        int inc = 0;
        for (int i = 0; i < str.Length; i++)
        {
            inc = str[i] > (char)255 ? 2 : 1;
            curIdx++;
            curLen += inc;
            if (curLen > len - 3)
            {
                if (cutIdx == 0)
                {
                    cutIdx = curIdx - 1;
                    cutLen = curLen - inc;
                }
                if (curLen > len)
                {
                    if (cutLen == len - 3)
                        return str.Substring(0, cutIdx).Trim() + "...";
                    else return str.Substring(0, cutIdx).Trim() + "...";
                }
            }
        }

        return str;
    }

    public static string UrlNocache(string url)
    {
        if (url.IndexOf("?") > 0)
            url += "&";
        else
            url += "?";
        url += "nocache=" + new Random().Next(10000);
        return url;
    }

    public static string CsStyledEncode(string s)
    {
        s = s.Replace("\\", "\\\\").Replace("'", "\\'").Replace("\"", "\\\"").Replace("\r\n", "\\n").Replace("\n\r", "\\n").Replace("\r", "\\n").Replace("\n", "\\n");
        s = s.Replace("/", "\\/");
        return s;
    }


    public static void SetPageReadOnly(System.Web.UI.Control parentControl)
    {
        foreach (Control ctrl in parentControl.Controls)
        {
            SetPageReadOnly(ctrl);

            if (ctrl is TextBox)
            {
                TextBox txt = (TextBox)ctrl;
                txt.ReadOnly = true;
                txt.CssClass = "ReadOnly";
            }
            if (ctrl is DropDownList)
            {
                DropDownList ddl = (DropDownList)ctrl;
                ddl.Enabled = false;
            }
            if (ctrl is RadioButtonList)
            {
                RadioButtonList rbl = (RadioButtonList)ctrl;
                rbl.Enabled = false;
            }

            if (ctrl is CheckBox)
            {
                CheckBox cb = (CheckBox)ctrl;
                cb.Enabled = false;
            }

            if (ctrl is LinkButton)
            {
                LinkButton lbtn = (LinkButton)ctrl;
                lbtn.Enabled = false;
            }

            if (ctrl is ImageButton)
            {
                ImageButton ibtn = (ImageButton)ctrl;
                ibtn.Enabled = false;
            }

        }
    }

    public static void ClearPageReadOnly(System.Web.UI.Control parentControl)
    {
        foreach (Control ctrl in parentControl.Controls)
        {
            ClearPageReadOnly(ctrl);

            if (ctrl is TextBox)
            {
                TextBox txt = (TextBox)ctrl;
                if (txt.ID != "tbSource")
                {
                    txt.ReadOnly = false; ;
                    txt.CssClass = "TextBox08";
                    if (txt.ID == "tbText")
                        txt.CssClass = "Textarea02";
                }
            }
            if (ctrl is DropDownList)
            {
                DropDownList ddl = (DropDownList)ctrl;
                ddl.Enabled = true;
            }
            if (ctrl is RadioButtonList)
            {
                RadioButtonList rbl = (RadioButtonList)ctrl;
                rbl.Enabled = true;
            }

            if (ctrl is CheckBox)
            {
                CheckBox cb = (CheckBox)ctrl;
                cb.Enabled = true;
            }

            if (ctrl is LinkButton)
            {
                LinkButton lbtn = (LinkButton)ctrl;
                lbtn.Enabled = true;
            }

            if (ctrl is ImageButton)
            {
                ImageButton ibtn = (ImageButton)ctrl;
                ibtn.Enabled = true;
            }
        }
    }

    public static string MonthIntToChinise(int month)
    {
        switch (month)
        { 
            case 1:
                return "一月份";
                break;
            case 2:
                return "二月份";
                break;
            case 3:
                return "三月份";
                break;
            case 4:
                return "四月份";
                break;
            case 5:
                return "五月份";
                break;
            case 6:
                return "六月份";
                break;
            case 7:
                return "七月份";
                break;
            case 8:
                return "八月份";
                break;
            case 9:
                return "九月份";
                break;
            case 10:
                return "十月份";
                break;
            case 11:
                return "十一月份";
                break;
            case 12:
                return "十二月份";
                break;
            default:
                return "";
        }
    }

    private static Guid _moduleID = Guid.Empty;
    public static Guid ModuleID
    {
        get
        {
            try
            {
                if (_moduleID == Guid.Empty)
                    _moduleID = new Guid(Wicresoft.Common.Configuration.ConfigurationSettings.AppSettings["Busi.ModuleID"].ToString());
                return _moduleID;
            }
            catch
            {
                return new Guid("{C44993EA-36D4-432B-972C-18AD52F5C323}");
            }
        }
    }

    private static long _maxUploadSize = long.MinValue;
    public static long MaxUploadSize
    {
        get
        {
            try
            {
                if (_maxUploadSize == long.MinValue)
                    _maxUploadSize = long.Parse(Wicresoft.Common.Configuration.ConfigurationSettings.AppSettings["MaxUploadSize"].ToString());
                return _maxUploadSize;
            }
            catch
            {
                return 4096000;
            }
        }
    }

    private static int _coverCount = int.MinValue;
    public static int CoverCount
    {
        get
        {
            try
            {
                if (_coverCount == int.MinValue)
                    _coverCount = int.Parse(Wicresoft.Common.Configuration.ConfigurationSettings.AppSettings["CoverCount"].ToString());
                return _coverCount;
            }
            catch
            {
                return 2;
            }
        }
    }

}
